package com.example.tool.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class CaiNiaoUtil {
    // 正式环境地址
    private static final String GATEWAY_URL = "https://link.cainiao.com/gateway/link.do";

    // 公共参数（需替换为实际值）
    private static final String APP_KEY = "001079";
    private static final String SECRET_KEY = "2pMwi809HFYD2ZsuN85Y75g5s56WxF8c";
    private static final String FROM_CODE = "85cc9d8bc03fc88ae20cd9f1944acdd2";
    private static final String MSG_TYPE = "trace_info_query";
    private static final String PARTNER_CODE = "partner_code";

    public static void main(String[] args) {
        try {
            // 1. 构建请求XML
            String cpCode = "YOUR_CP_CODE";
            List<String> mailNos = Arrays.asList("SF123456789", "SF987654321");
            StringBuilder xmlBuilder = new StringBuilder();
            xmlBuilder.append("<request>");
            xmlBuilder.append("<cpCode>").append(cpCode).append("</cpCode>");
            xmlBuilder.append("<mailNos>");
            for (String mailNo : mailNos) {
                xmlBuilder.append("<mailNo>").append(mailNo).append("</mailNo>");
            }
            xmlBuilder.append("</mailNos>");
            xmlBuilder.append("</request>");
//            String requestXml = buildRequestXml(cpCode, mailNos);

            // 2. 计算签名（data_digest）
            String dataDigest = calculateDigest(xmlBuilder.toString(), SECRET_KEY);

            // 3. 准备公共参数
            Map<String, String> publicParams = new HashMap<>();
            publicParams.put("msg_type", "trace_info_query");
            publicParams.put("msg_id", UUID.randomUUID().toString());
            publicParams.put("from_code", FROM_CODE);
            publicParams.put("partner_code", "123123123123");
            publicParams.put("data_digest", dataDigest);
            publicParams.put("logistics_interface", xmlBuilder.toString());

            // 4. 发送HTTP请求
            String response = sendPostRequest(GATEWAY_URL, publicParams);

            // 5. 解析响应
            System.out.println("响应结果:\n" + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 构建XML请求体
     */
    private static String buildRequestXml(String cpCode, List<String> mailNos) {
        StringBuilder xmlBuilder = new StringBuilder();
        xmlBuilder.append("<request>");
        xmlBuilder.append("<cpCode>").append(cpCode).append("</cpCode>");
        xmlBuilder.append("<mailNos>");
        for (String mailNo : mailNos) {
            xmlBuilder.append("<mailNo>").append(mailNo).append("</mailNo>");
        }
        xmlBuilder.append("</mailNos>");
        xmlBuilder.append("</request>");
        return xmlBuilder.toString();
    }

    /**
     * 计算签名（data_digest）
     */
    private static String calculateDigest(String xml, String secretKey) {
        String content = xml + secretKey;
        return DigestUtils.md5Hex(content.getBytes(StandardCharsets.UTF_8)).toUpperCase();
    }

    /**
     * 发送HTTP POST请求
     */
    private static String sendPostRequest(String url, Map<String, String> params) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept-Charset", "UTF-8");
            // 设置表单参数
            List<org.apache.http.NameValuePair> formParams = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                formParams.add(new org.apache.http.message.BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8));
            // 使用URL编码格式
            httpPost.setEntity(new StringEntity(
                    EntityUtils.toString(new org.apache.http.client.entity.UrlEncodedFormEntity(formParams)),
                    StandardCharsets.UTF_8));
            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity, StandardCharsets.UTF_8); // 关键修复
            }
        }
    }
}
